package com.fengwei.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author fengwei
 * @date 2018/9/3 为了防止inputstream在拦截器只能读取一次
 */
@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*", filterName = "RepeatedlyReadFilter")
public class RepeatedlyReadFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(RepeatedlyReadFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        ServletRequest requestWrapper = null;

        if (request instanceof HttpServletRequest) {
            String servletPath = ((HttpServletRequest) request).getServletPath();
            // logger.debug("servletPath:"+servletPath);
            if ("OPTIONS".equals(((HttpServletRequest) request).getMethod())) {
                chain.doFilter(request, response);
                return;
            }

            if ("GET".equals(((HttpServletRequest) request).getMethod())) {
                chain.doFilter(request, response);
                return;
            }

            requestWrapper = new RepeatedlyReadRequestWrapper((HttpServletRequest) request);
            chain.doFilter(requestWrapper, response);
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}